package com.tsugun.mediaplayer.view.loader;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.DrawableRes;
import android.support.v7.graphics.Palette;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.ArtistModel;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.presenter.cache.DoubleCache;
import com.tsugun.mediaplayer.presenter.cache.ImageCache;
import com.tsugun.mediaplayer.presenter.utils.BitmapHelper;
import com.tsugun.mediaplayer.presenter.utils.ConverterHelper;
import com.tsugun.mediaplayer.presenter.utils.HttpHelper;
import com.tsugun.mediaplayer.presenter.utils.SystemHelper;
import com.tsugun.mediaplayer.view.activity.BaseActivity;

import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 音乐图片加载器
 * Created by shize on 2017/4/17.
 */

public class MediaImageLoad {
    private static ImageCache mCache = new DoubleCache(); // 缓存
    private static ExecutorService mExecutorService = Executors.newFixedThreadPool(
            Runtime.getRuntime().availableProcessors());

    private static int SIZE_CACHE_IMAGE = 720; // 缓存图片尺寸
    private static final int COLOR_DEFAULT = 0xfffafafa; // 默认背景色

    private static int PREV_COLOR = 0xfffafafa; // 记录上一次的颜色

    private MediaImageLoad() {
    }

    /**
     * 设置缓存模式
     *
     * @param cacheMode implements ImageCache
     */
    public static void setCacheMode(ImageCache cacheMode) {
        mCache = cacheMode;
    }

    /**
     * 设置缓存图片的尺寸
     *
     * @param cacheSize 尺寸
     */
    public static void setCacheSize(int cacheSize) {
        SIZE_CACHE_IMAGE = cacheSize;
    }

    /**
     * @return 获取缓存图片的尺寸
     */
    public static int getCacheSize() {
        return SIZE_CACHE_IMAGE;
    }

    /**
     * 子线程加载图片
     *
     * @param bitmap    图片
     * @param imageView 图片容器
     */
    public static void loadBitmap(final Bitmap bitmap, final ImageView imageView) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                setImage(bitmap, imageView);
            }
        });
    }

    /**
     * 通过id在子线程加载drawable资源
     *
     * @param resId     资源id
     * @param imageView 图片容器
     */
    public static void loadDrawableById(@DrawableRes final int resId, final ImageView imageView) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                BitmapFactory.Options options = new BitmapFactory.Options();
                // 设置编码格式RGB_565
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                options.inSampleSize = 2; // 压缩图片,值为压缩倍数
                setImage(BitmapFactory.decodeResource(imageView.getResources(), resId, options),
                        imageView);
            }
        });
    }

    /**
     * 加载图片
     */
    public static void localImageLoad(final MusicModel musicModel, final ImageView imageView) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = mCache.get(musicModel.getAlbum());
                // 为空则获取
                if (bitmap == null) {
                    localMusicImageLoadByThread(musicModel, imageView);
                    return;
                }
                // 在加载列表时，最好在子线程读取SDCard中的图片（IO流还是比较耗时的）
                setImage(bitmap, imageView);
            }
        });
    }

    /**
     * 锁屏加载图片
     */
    public static void lockImageLoad(final MusicModel musicModel, final ImageView imageView) {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                // 锁屏直接使用原图
                Bitmap bitmap = BitmapHelper.INSTANCE.getBitmapFromMedia(musicModel.getUrl());
                // 为空则获取
                if (bitmap == null) {
                    return;
                }
                // 在加载列表时，最好在子线程读取SDCard中的图片（IO流还是比较耗时的）
                setImage(bitmap, imageView);
            }
        });
    }

    /**
     * 在本地获取多媒体文件图片数据
     *
     * @param musicModel 音乐
     */
    private static void localMusicImageLoadByThread(final MusicModel musicModel, final ImageView imageView) {
        final String musicUrl = musicModel.getUrl();
        imageView.setTag(musicUrl);
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = BitmapHelper.INSTANCE.getBitmapFromMedia(musicUrl);
                // 防止图片错位
                if (!imageView.getTag().equals(musicUrl)) {
                    return;
                }
                if (bitmap != null) {
                    mCache.put(musicModel.getAlbum(), bitmap);
                    // 插入系统数据库(MIUI会自动插入系统数据库)
//                    SystemHelper.insertImage(imageView.getContext(), ConverterHelper.getConvertedAlbumPath(
//                            musicModel.getAlbum()), musicModel.getAlbum());
                }
                // view.post()方法存在不能100%执行的风险
                setImage(bitmap, imageView);
            }
        });
    }

    /**
     * 给view设置图片
     *
     * @param bitmap    图片
     * @param imageView view
     */
    private synchronized static void setImage(final Bitmap bitmap, final ImageView imageView) {
        Activity a = (Activity) imageView.getContext();
        a.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (bitmap == null) {
                    imageView.setImageResource(R.mipmap.img_default);
                    return;
                }
                startAnimator(imageView, bitmap);
            }
        });
        setBackground(bitmap, ((View) imageView.getParent()).findViewById(R.id.id_back_color));
    }

    /**
     * 设置背景颜色
     *
     * @param bitmap 要萃取颜色的图片
     */
    private static void setBackground(Bitmap bitmap, final View view) {
        if (view == null) {
            return;
        }
        if (bitmap == null) {
            changeColorAnimator(COLOR_DEFAULT, view);
            return;
        }
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                int color = palette.getDominantColor(COLOR_DEFAULT);
                changeColorAnimator(color, view);
            }
        });
    }

    /**
     * 修改颜色动画
     *
     * @param color 颜色
     * @param view  变化 view
     */
    private static void changeColorAnimator(int color, final View view) {
        ValueAnimator animator = ValueAnimator.ofInt(PREV_COLOR, color);
        animator.setDuration(200);
        animator.setEvaluator(new ArgbEvaluator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setBackgroundColor((Integer) animation.getAnimatedValue());
            }
        });
        animator.start();
        PREV_COLOR = color;
        ((BaseActivity)view.getContext()).setBgColor(color);
    }

    /**
     * 开启切换淡入淡出动画
     */
    private static void startAnimator(final ImageView imageView, final Bitmap bitmap) {
        AlphaAnimation enter = new AlphaAnimation(0, 1);
        enter.setDuration(400);
        enter.setFillAfter(true);
        imageView.clearAnimation();
        imageView.startAnimation(enter);
        imageView.setImageBitmap(bitmap);
    }

    /**
     * 加载网络上的歌手写真
     *
     * @param artist    歌手名
     * @param imageView 图片容器
     */
    public static void netArtistImageLoad(final ArtistModel artist, final ImageView imageView) {
        if (SystemHelper.INSTANCE.isMobile(imageView.getContext())) {
            Log.d("isMobile", "netArtistImageLoad: 数据流量！！！");
            return;
        }
        imageView.setTag(artist);
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = mCache.get(artist.getImageUrl());
                // bitmap为空则在网络上下载
                if (bitmap == null) {
                    URL url = HttpHelper.INSTANCE.getImageURL(artist.getName());
                    if (url != null) {
                        artist.setImageUrl(ConverterHelper.INSTANCE.getConvertedAlbumPath(url.toString()));
                        bitmap = HttpHelper.INSTANCE.downloadBitmap(url);
                    }
                }
                if (bitmap != null && imageView.getTag().equals(artist)) {
                    setImage(bitmap, imageView);
                    mCache.put(artist.getImageUrl(), bitmap);
                }
            }
        });
    }

}
